import { tplReplace, filterData } from '../utils/tools';
import bookItemTpl from '../templates/bookItem.tpl';
import { URL } from '../config/config';

export default ($) => {

    const $navList = $('.J_navList'),
          $bookList = $('.J_bookList'),
          $navItems = $navList.children('.nav-item'),
          bookData = $.parseJSON($('.J_bookData').html());

    const init = () => {
        bindEvent();
    }

    function bindEvent () {
        $navList.on('click', '.nav-lk', onNavClick);
    }

    function onNavClick () {
        const $this = $(this),
              curIdx = $this.parent().index(),
              id = parseInt($this.attr('data-id')),
              data = filterData(bookData, id);

        tabChange(curIdx);
        renderList(data);
    }

    function tabChange (index) {
        $navItems.eq(index).addClass('current')
                 .siblings().removeClass('current');
    }

    function renderList (data) {
        // console.log(data);
        let list = '';

        data.forEach((item, index) => {
            list += tplReplace(bookItemTpl, {
                imgKey: URL.IMG_BASE_URL + item.imgKey,
                bookTitle: item.bookTitle,
                priceClass: item.bookPrice == '0' ? 'left free' : 'left price',
                bookPrice: item.bookPrice == '0' ? '免费' : `￥${item.bookPrice}`,
                readCount: Math.floor(Math.random() * 1000)
            })
        });

        $bookList.html(list);
    }

    return {
        init
    }
}